Matrix Selection and Indexing

Just like with vectors, we use the square bracket notation to select elements from a matrix. Since we have two dimensions to work with, we'll use a comma to separate our indexing for each dimension.

So the syntax is then:

example.matrix[rows,columns]

where the index notation (e.g. 1:5) is put in place of the rows or columns . If either rows or columns is left blank, then we are selecting all the rows and columns.

Let's work through some examples:

In [1]:
mat <- matrix(1:50,byrow=TRUE,nrow=5)
In [2]:
mat
Out[2]:
1 2 3 4 5 6 7 8 910
11121314151617181920
21222324252627282930
31323334353637383940
41424344454647484950
In [3]:
# Grab first row
mat[1,]
Out[3]:
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
In [4]:
#Grab first column
mat[,1]
Out[4]:
  1. 1
  2. 11
  3. 21
  4. 31
  5. 41
In [6]:
# Grab first 3 rows
mat[1:3,]
Out[6]:
1 2 3 4 5 6 7 8 910
11121314151617181920
21222324252627282930
In [8]:
# Grab top left rectangle of:
# 1,2,3
# 11,12,13
#
mat[1:2,1:3]
Out[8]:
123
111213
In [9]:
# Grab last two columns
mat[,9:10]
Out[9]:
910
1920
2930
3940
4950
In [14]:
# Grab a center square of:
# 15,16
# 25,26
mat[2:3,5:6]
Out[14]:
1516
2526

Great job! You should practice this! Just pick out blocks from the matrix and see if you can successfully index them. Up next we will learn about Matrix Arithmetic!